package com.jky.trial.controller;

import com.jky.trial.common.BaseResult;
import com.jky.trial.common.ListResult;
import com.jky.trial.common.jwt.JWTUtil;
import com.jky.trial.constant.DataStatus;
import com.jky.trial.constant.PermissionConstant;
import com.jky.trial.entity.Category;
import com.jky.trial.entity.Project;
import com.jky.trial.entity.Task;
import com.jky.trial.entity.User;
import com.jky.trial.service.CategoryService;
import com.jky.trial.service.ExportService;
import com.jky.trial.service.ProjectService;
import com.jky.trial.service.TaskService;
import com.jky.trial.vo.TaskVo;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/v1/task")
public class TaskController {

    private TaskService recordService;
    private ExportService exportService;
    private CategoryService categoryService;
    private ProjectService projectService;

//    private MapController mapController;

    @Autowired
    TaskController(TaskService recordService, ExportService exportService,
//            ,MapController mapController
                   ProjectService projectService,
                   CategoryService categoryService
    ) {
        this.recordService = recordService;
        this.projectService = projectService;
        this.categoryService = categoryService;
        this.exportService = exportService;
    }

    @PostMapping
    public BaseResult create(@RequestBody Task record, HttpServletRequest request) {
        User user = JWTUtil.getUser(request.getHeader("tk"));
        record.setCreatorId(user.getId());
        recordService.create(record);
        return new BaseResult(true, record.getId());
    }

    /**
     * 技术分配任务
     *
     * @param record
     * @return
     */
    @PutMapping("/assign")
    public BaseResult assign(@RequestBody Task record, HttpServletRequest request) {
        User user = JWTUtil.getUser(request.getHeader("tk"));
        return new BaseResult(true, recordService.assign(record, user));
    }

    /**
     * 描述员提交任务
     *
     * @param record
     * @return
     */
    @PutMapping("/submit")
    public BaseResult submit(@RequestBody Task record, HttpServletRequest request) {
        User user = JWTUtil.getUser(request.getHeader("tk"));
        return new BaseResult(true, recordService.submit(record, user));
    }

    /**
     * 技术负责人审核勘探点描述
     *
     * @param record
     * @param request
     * @return
     */
    @PutMapping("/check")
    public BaseResult check(@RequestBody Task record, HttpServletRequest request) {
        User user = JWTUtil.getUser(request.getHeader("tk"));
        return new BaseResult(true, recordService.check(record, user));
    }

    @PutMapping
    public BaseResult update(@RequestBody Task record) {
        Task task2 = recordService.detail(record.getId());
        if (task2 != null) {
            projectService.updateProgress(task2.getProjectId());
        }
        return new BaseResult(true, recordService.update(record));
    }

    @RequiresPermissions(PermissionConstant.DELETE_TASK)
    @DeleteMapping("/{id}")
    public BaseResult del(@PathVariable Integer id) {

        Task task2 = recordService.detail(id);
        if (task2 != null) {
            projectService.updateProgress(task2.getProjectId());
        }
        return new BaseResult(true, recordService.del(id));
    }


    @RequiresPermissions(PermissionConstant.DELETE_BATCH_TASK)
    @DeleteMapping("/dels/{ids}")
    public BaseResult dels(@PathVariable String ids) {
        String[] id1s = ids.split(",");
        for (int i = 0; i < id1s.length; i++) {
            recordService.del(Integer.parseInt(id1s[i]));
        }



        return new BaseResult(true, null, 200);
    }

    /**
     * 批量导入勘察点
     *
     * @param file      excel文件
     * @param projectId 项目ID
     * @param request
     * @param response
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/import", method = RequestMethod.POST)
    public BaseResult importData(@RequestParam("file") MultipartFile file,
                                 Integer projectId,//项目ID
                                 HttpServletRequest request, HttpServletResponse response) throws IOException {
        User user_ = JWTUtil.getUser(request.getHeader("tk"));
        if (file.isEmpty()) {
            return new BaseResult(false, "file is empty", 400);
        }
        response.setHeader("Content-type", "text/html");
        List<Task> list = exportService.importTaskExcel(file.getInputStream(), projectId, user_.getId());
        if(list.size()>0){
            Map map = MapController.getAddressByLonLat(list.get(0).getLonLat());
            Project project = new Project();
            project.setId(projectId);
            project.setAddress(map.get("address").toString());
            Category category = new Category();
            category.setType(DataStatus.CATEGORY_DATA_TYPE_COUNTRY.getVal());
            category.setName(map.get("c").toString());
            category.setDeleted(false);
            Category category1 = categoryService.selectOne(category);
            if(category1!=null){
                project.setCountryId(category1.getId());
            }
            category.setName(map.get("p").toString());
            category.setType(DataStatus.CATEGORY_DATA_TYPE_PROVINCE.getVal());
            Category category2 = categoryService.selectOne(category);
            if(category2!=null){
                project.setProvinceId(category2.getId());
            }
            category.setName(map.get("c1").toString());
            category.setType(DataStatus.CATEGORY_DATA_TYPE_CITY.getVal());
            Category category3 = categoryService.selectOne(category);
            if(category3!=null){
                project.setCityId(category3.getId());
            }
            projectService.update(project);

        }
        return recordService.importTask(list);
    }

    @GetMapping("/{id}")
    public BaseResult get(@PathVariable Integer id) {
        return new BaseResult(true, recordService.detail(id));
    }

    @GetMapping("/moreDetail/{id}")
    public BaseResult moreDetail(@PathVariable Integer id) {
        return new BaseResult(true, recordService.moreDetail(id));
    }

    @GetMapping("/page/{projectId}")
    public ListResult page(TaskVo record) {
        return recordService.page(record);
    }

    /**
     * 地图统计信息
     * @param record
     * @return
     */
    @GetMapping("/mapData/{projectId}")
    public BaseResult mapData(TaskVo record) {
        return recordService.mapData(record);
    }

    /**
     * 描述员
     *
     * @param record
     * @return
     */
    @GetMapping("/msy/page")
    public ListResult msyPage(TaskVo record, HttpServletRequest request) {
        String id = JWTUtil.getId(request.getHeader("tk"));
        record.setAssigneeId(Integer.valueOf(id));
        return recordService.msyPage(record);
    }

    @GetMapping("/msyWithProjectName/page")
    public ListResult msyWithProjectName(TaskVo record, HttpServletRequest request) {
        String id = JWTUtil.getId(request.getHeader("tk"));
        record.setAssigneeId(Integer.valueOf(id));
        return recordService.msyWidthProjectNamePage(record);
    }


    @GetMapping("/list")
    public ListResult list(TaskVo record) {
        return new ListResult(true, recordService.list(record));
    }
}
